package com.wxp.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.models.constant.JafCoreConstant;
import com.modules.utils.BeanUtils;
import com.wxp.dao.PermissionDao;
import com.wxp.dao.RoleDao;
import com.wxp.entity.Permission;
import com.wxp.entity.Resource;
import com.wxp.entity.Role;
import com.wxp.mapper.RoleMapper;
import com.wxp.service.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private PermissionDao permissionDao;

    public Page<Role> findAll(Pageable pageable){

        return this.roleDao.findAll(pageable);
    }
    public Page<Role> findAll(Specification spec,PageRequest pageRequest){
        return this.roleDao.findAll(spec,pageRequest);
    }
    
	@Override
	public String save(Role role) {
		String result = null;
		String primaryKey = role.getRoleCode();
		Role existed = null;
		if (!StringUtils.isEmpty(primaryKey)) {
			existed = roleDao.findOne(primaryKey);
		}
		if(existed == null) {
		
			roleDao.save(role);
			result = JafCoreConstant.SAVE_SUCCESS;
		}else {
			
			if ((existed.getVersion() != null) && (existed.getVersion().intValue() != role.getVersion().intValue())){
				result = JafCoreConstant.OUT_OF_DATE;//已经被别人编辑更新过了
			}else {
				String[] properties = new String[] {"roleName","roleDesc"};
				BeanUtils.copyAssignProperties(role, existed, properties);
				this.roleDao.save(existed);
				result = JafCoreConstant.UPDATE_SUCCESS;
			}
			result = JafCoreConstant.UPDATE_SUCCESS;
		}
		return result;
	}
	@Override
	public void savePermission(String roleCode, String data) {
		ArrayList<Resource> resourceList = JSON.parseObject(data, new TypeReference<ArrayList<Resource>>() {});
		//删除roleCode对应的角色
		permissionDao.deleteByRoleCode(roleCode);
		for(Resource resource:resourceList) {
			Permission permission = new Permission();
			permission.setOperatorId(resource.getOperator());
			permission.setOperatorName(resource.getOperatorName());
			permission.setRoleCode(roleCode);
			permission.setPermission(resource.getPermission());
			permission.setRole(roleDao.findOne(roleCode));
			permissionDao.save(permission);
		}
		
	}
	
	@Override
	public List<Role> findUserRoleAll(String userId) {
		return roleMapper.findUserRoleAll(userId);
	}

}
